//
//  WmcHomeVC+VideoRecording.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/7.
//

import UIKit
import YPBedrock

extension WmcHomeVC {
    /// 视频模式
    func videoMode() {
        // 顶部
        headerView.switchMode(.video, cameraView: cameraView)
        // 底部
        footerView.switchMode(.video)
        // 中部
        switchMode(.video)
        // 切换至视频16-9
        setAspectRatio(.ar_16_9, animated: true)
        autoFrame()
        positioningBtn.isHidden = false
    }

    /// 视频录制模式
    func videoRecordingState() {
        // UI调整
        positioningBtn.isHidden = true
        videoRecordingLabel.isHidden = false
        functionSelectView.isHidden = true
        // 停止水印交互，并移到屏幕外
        watermarkContentView.isUserInteractionEnabled = false
        var wmRect = watermarkContentView.frame
        wmRect.origin.x = Wmc_screenWidth
        watermarkContentView.frame = wmRect
        // 显示官方水印
        if !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark {
            watermarkContentView.showOfficialWatermark()
        }
        // 停止陀螺仪
        WmcMotionManager.shared.stop()
        // 相机添加水印
        updateVideoWatermarkScreenshot()
    }

    /// 视频结束录制模式
    func videoEndRecordingState() {
        positioningBtn.isHidden = false
        videoRecordingLabel.isHidden = true
        functionSelectView.isHidden = false
        // 开启陀螺仪
        WmcMotionManager.shared.start()
        // 开启水印交互，将水印移回来
        watermarkContentView.isUserInteractionEnabled = true
        watermarkContentView.frame = cameraBackgroundView.frame
        // 隐藏官方水印
        watermarkContentView.hideOfficialWatermark()
        // 移除所有水印
        cameraView?.removeAllWatermark()
    }

    /// 视频更新水印截图
    func updateVideoWatermarkScreenshot() {
        guard (viewModel.videoRecordState == .being ||
            viewModel.videoRecordState == .pause) else { return }
            updateWatermarkScreenshot()
    }

    /// 更新水印到相机预览
    func updateWatermarkScreenshot() {
        controlView.stopFlashDottedLayer() // 停止闪烁

        let size = watermarkContentView.bounds.size
        guard size.width > 0 && size.height > 0 else { return }
        UIGraphicsBeginImageContextWithOptions(size, false, 2)
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.scaleBy(x: 1, y: 1)
        watermarkContentView.layer.render(in: ctx)
        let _wmImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let wmImage = _wmImage else { return }

        // 旋转原图
        // 询问外部代理支持的方向
        var defaultOrientation: [UIDeviceOrientation] = viewModel.defaultOrientation
        if let _defaultOrientation = homeDelegate?.cameraRotatingOrientation(.current,
                                                                             functionMode: viewModel.functionMode,
                                                                             videoRecordState: viewModel.videoRecordState,
                                                                             defaultOrientation: defaultOrientation)
        {
            defaultOrientation = _defaultOrientation
        }
        let orientation = WmcMotionManager.shared.orientation.value

        var angleWmImage: UIImage? = wmImage
        if defaultOrientation.contains(orientation) {
            var angle: CGFloat = 0
            switch WmcMotionManager.shared.orientation.value {
            case .landscapeRight: angle = 270 // 右
            case .portraitUpsideDown: angle = 180 // 反向
            case .landscapeLeft: angle = 90 // 左
            default: break
            }
            angleWmImage = wmImage.yp.setRotate(angle: angle)
        }

        guard let angleWmImage = angleWmImage else { return }
        let watermarkCount = cameraView?.watermarkCount() ?? 0
        if watermarkCount <= 0 {
            cameraView?.appendWatermark(image: angleWmImage, blendMode: .coincidence)
        } else {
            cameraView?.replaceWatermark(image: angleWmImage, at: 0)
        }
    }

    // MARK: 录制方法

    /// 执行开始录制
    func startRecording() {
        WatermarkCameraLib.Log("视频操作：点击录制视频")
        guard viewModel.videoRecordState == .stop else { return }
        WatermarkCameraLib.Log("视频操作：开始录制视频")
        // 禁止息屏
        UIApplication.shared.isIdleTimerDisabled = true

        // 状态
        let recordingState: VideoRecordState = .being
        viewModel.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState, cameraView: cameraView)
        // 中部
        self.videoRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        // 隐式
        viewModel.startRecordingTimer()
        // 临时写入路径
        let url = URL(fileURLWithPath: "\(NSTemporaryDirectory())/\(Date().timeIntervalSince1970).mp4")
        let orientation = WmcMotionManager.shared.orientation.value.yp.uiInterfaceOrientation
        // 询问代理设置清晰度
        if let watermarkModel = watermarkContentView.watermarkModel,
           let currentArticulation = cameraView?.writerArticulation(),
           let articulation = homeDelegate?.videoRecordArticulation(.current,
                                                                    watermarkModel: watermarkModel,
                                                                    currentArticulation: currentArticulation) {
            cameraView?.setWriterArticulation(articulation)
        }
        // 开始录制
        cameraView?.startCollectVideo(fileUrl: url, orientation: .orientation(orientation))
    }

    /// 继续录制
    func continueRecording() {
        WatermarkCameraLib.Log("视频操作：点击继续录制")
        guard viewModel.videoRecordState == .pause else { return }
        WatermarkCameraLib.Log("视频操作：继续录制视频")
    
        // 状态
        let recordingState: VideoRecordState = .being
        viewModel.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState, cameraView: cameraView)
        // 中部
        self.videoRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        cameraView?.continueCollectVideo()
    }

    /// 暂停录制
    func pauseRecording() {
        WatermarkCameraLib.Log("视频操作：点击暂停录制")
        guard viewModel.videoRecordState == .being else { return }
        WatermarkCameraLib.Log("视频操作：暂停录制视频")
        // 状态
        let recordingState: VideoRecordState = .pause
        viewModel.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState, cameraView: cameraView)
        // 中部
        self.videoRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)

        footerView.pauseVideoRecordBtn.isUserInteractionEnabled = false
        cameraView?.pauseCollectVideo { [weak self] in // 暂停完成
            guard let weakSelf = self else { return }
            weakSelf.footerView.pauseVideoRecordBtn.isUserInteractionEnabled = true
        }
    }

    /// 停止录制
    /// - Parameter breakOffType: 是否是被迫中断，如来电或回后台
    func stopRecording(breakOffType: WmcHomeVM.BreakOffType) {
        WatermarkCameraLib.Log("视频操作：点击停止录制")
        guard (viewModel.videoRecordState == .being ||
            viewModel.videoRecordState == .pause) else { return }
        WatermarkCameraLib.Log("视频操作：停止录制视频")
        // 允许息屏
        UIApplication.shared.isIdleTimerDisabled = false
        // 状态
        let recordingState: VideoRecordState = .stop
        viewModel.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState, cameraView: cameraView)
        // 中部
        self.videoEndRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        // 隐式
        viewModel.stopRecordingTimer()

//        WmcHudManager.toast("\n视频处理中...\n")
        cameraView?.stopCollectVideo { [weak self] url in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.saveVideo(url: url, watermarkModel: weakSelf.viewModel.watermarkRelay.value, breakOffType: breakOffType)
//            WmcHudManager.toast("\n视频处理完成!\n")
        }
    }
}
